<template>
  <div class="min-h-screen bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
      <!-- 页面标题 -->
      <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-900">章节要点配置管理</h1>
        <p class="mt-2 text-gray-600">管理各章节的要点配置信息</p>
      </div>

      <!-- 操作按钮 -->
      <div class="mb-6 flex justify-between items-center">
        <div class="flex space-x-4">
          <!-- 搜索和筛选 -->
          <div class="relative">
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索标题..."
              class="w-64 pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            />
            <svg class="absolute left-3 top-2.5 h-5 w-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"></path>
            </svg>
          </div>
          
          <select
            v-model="selectedChapter"
            class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">所有章节</option>
            <option v-for="chapter in availableChapters" :key="chapter" :value="chapter">
              第{{ chapter }}章
            </option>
          </select>
          
          <select
            v-model="selectedStatus"
            class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
          >
            <option value="">所有状态</option>
            <option value="true">启用</option>
            <option value="false">禁用</option>
          </select>
        </div>
        
        <div class="flex space-x-4">
          <button
            @click="openCreateModal"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6"></path>
            </svg>
            <span>新增要点配置</span>
          </button>
          <button
            @click="loadHighlights"
            class="bg-gray-600 text-white px-4 py-2 rounded-lg hover:bg-gray-700 transition-colors flex items-center space-x-2"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
            <span>刷新</span>
          </button>
        </div>
      </div>

    <!-- 加载状态 -->
      <div v-if="loading" class="flex justify-center items-center py-12">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span class="ml-2 text-gray-600">加载中...</span>
      </div>

      <!-- 错误信息 -->
      <div v-if="error" class="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
        <div class="flex items-center">
          <svg class="w-5 h-5 text-red-400 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
          </svg>
          <span class="text-red-800">{{ error }}</span>
        </div>
      </div>

    <!-- 章节要点配置列表 -->
      <div v-if="!loading && filteredHighlights.length > 0" class="bg-white shadow-lg rounded-lg overflow-hidden">
        <div class="overflow-x-auto">
          <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
              <tr>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">章节</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">左侧标题</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">右侧标题</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">排序</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
              </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">
              <tr v-for="highlight in paginatedHighlights" :key="highlight.id" class="hover:bg-gray-50">
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm font-medium text-gray-900">第{{ highlight.chapterNumber }}章</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-900">{{ highlight.title }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-600">{{ highlight.leftSection?.title || '-' }}</div>
                </td>
                <td class="px-6 py-4">
                  <div class="text-sm text-gray-600">{{ highlight.rightSection?.title || '-' }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <div class="text-sm text-gray-600">{{ highlight.sortOrder }}</div>
                </td>
                <td class="px-6 py-4 whitespace-nowrap">
                  <span :class="highlight.isActive ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'" 
                        class="inline-flex px-2 py-1 text-xs font-semibold rounded-full">
                    {{ highlight.isActive ? '启用' : '禁用' }}
                  </span>
                </td>
                <td class="px-6 py-4 whitespace-nowrap text-sm font-medium">
                  <div class="flex space-x-2">
                    <button
                      @click="editHighlight(highlight)"
                      class="text-blue-600 hover:text-blue-900 transition-colors"
                    >
                      编辑
                    </button>
                    <button
                      @click="toggleStatus(highlight)"
                      :class="highlight.isActive ? 'text-red-600 hover:text-red-900' : 'text-green-600 hover:text-green-900'"
                      class="transition-colors"
                    >
                      {{ highlight.isActive ? '禁用' : '启用' }}
                    </button>
                    <button
                      @click="deleteHighlight(highlight)"
                      class="text-red-600 hover:text-red-900 transition-colors"
                    >
                      删除
                    </button>
                  </div>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && filteredHighlights.length > 0 && totalPages > 1" class="mt-6 flex justify-center">
        <nav class="flex items-center gap-2">
          <button
            @click="currentPage = Math.max(1, currentPage - 1)"
            :disabled="currentPage === 1"
            class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            上一页
          </button>
          
          <span class="px-3 py-2 text-sm text-gray-700">
            第 {{ currentPage }} 页，共 {{ totalPages }} 页
          </span>
          
          <button
            @click="currentPage = Math.min(totalPages, currentPage + 1)"
            :disabled="currentPage === totalPages"
            class="px-3 py-2 text-sm font-medium text-gray-500 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
          >
            下一页
          </button>
        </nav>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredHighlights.length === 0" class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path>
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">暂无章节要点配置</h3>
        <p class="mt-1 text-sm text-gray-500">开始创建第一个章节要点配置</p>
        <div class="mt-6">
          <button
            @click="openCreateModal"
            class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
          >
            新增要点配置
          </button>
        </div>
      </div>
    </div>



    <!-- 章节要点配置模态框 -->
    <ChapterHighlightsModal
      v-if="showModal"
      :highlight="currentHighlight"
      :is-edit="isEdit"
      @close="closeModal"
      @save="handleSave"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useAuthStore } from '@/stores/auth'
import ChapterHighlightsModal from '@/components/ChapterHighlightsModal.vue'

// 从环境变量读取API基础地址
const API_BASE_URL = `http://${import.meta.env.VITE_BACKEND_HOST}:${import.meta.env.VITE_BACKEND_PORT}`

// 类型定义
interface SubSection {
  title: string
  color: string
  type: 'list' | 'text'
  items?: string[]
  content?: string
}

interface Section {
  title: string
  icon: string
  subsections: SubSection[]
}

interface Tip {
  label: string
  content: string
}

interface ChapterHighlight {
  id: number
  chapterNumber: number
  title: string
  leftSection: Section
  rightSection: Section
  tip: Tip
  isActive: boolean
  sortOrder: number
  createdBy: number
  updatedBy: number
  createdAt: string
  updatedAt: string
}



const authStore = useAuthStore()

// 状态管理
const loading = ref(false)
const error = ref('')
const highlights = ref<ChapterHighlight[]>([])
const showModal = ref(false)
const currentHighlight = ref<ChapterHighlight | null>(null)
const isEdit = ref(false)

// 搜索和筛选
const searchQuery = ref('')
const selectedChapter = ref('')
const selectedStatus = ref('')

// 分页
const currentPage = ref(1)
const pageSize = ref(10)



// 计算属性
const availableChapters = computed(() => {
  const chapters = [...new Set(highlights.value.map(h => h.chapterNumber))]
  return chapters.sort((a, b) => a - b)
})

const filteredHighlights = computed(() => {
  let filtered = highlights.value

  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(h => 
      h.title.toLowerCase().includes(query) ||
      h.leftSection?.title?.toLowerCase().includes(query) ||
      h.rightSection?.title?.toLowerCase().includes(query)
    )
  }

  // 章节过滤
  if (selectedChapter.value) {
    filtered = filtered.filter(h => h.chapterNumber === parseInt(selectedChapter.value))
  }

  // 状态过滤
  if (selectedStatus.value !== '') {
    filtered = filtered.filter(h => h.isActive === (selectedStatus.value === 'true'))
  }

  return filtered.sort((a, b) => {
    if (a.chapterNumber !== b.chapterNumber) {
      return a.chapterNumber - b.chapterNumber
    }
    return a.sortOrder - b.sortOrder
  })
})

// 分页相关计算属性
const totalPages = computed(() => {
  return Math.ceil(filteredHighlights.value.length / pageSize.value)
})

const paginatedHighlights = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredHighlights.value.slice(start, end)
})



// 方法
const loadHighlights = async () => {
  loading.value = true
  error.value = ''
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-highlights`, {
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      throw new Error('获取章节要点配置失败')
    }
    
    const result = await response.json()
    if (result.success) {
      highlights.value = result.data || []
    } else {
      throw new Error(result.message || '获取章节要点配置失败')
    }
  } catch (err) {
    error.value = err instanceof Error ? err.message : '获取章节要点配置失败'
    console.error('加载章节要点配置失败:', err)
  } finally {
    loading.value = false
  }
}

const openCreateModal = () => {
  currentHighlight.value = null
  isEdit.value = false
  showModal.value = true
}

const openEditModal = (highlight: ChapterHighlight) => {
  currentHighlight.value = { ...highlight }
  isEdit.value = true
  showModal.value = true
}

const editHighlight = (highlight: ChapterHighlight) => {
  openEditModal(highlight)
}

const closeModal = () => {
  showModal.value = false
  currentHighlight.value = null
  isEdit.value = false
}

const handleSave = async (highlightData: Partial<ChapterHighlight>) => {
  try {
    const url = isEdit.value 
      ? `${API_BASE_URL}/api/chapter-highlights/${currentHighlight.value?.id}`
      : `${API_BASE_URL}/api/chapter-highlights`
    
    const method = isEdit.value ? 'PUT' : 'POST'
    
    const response = await fetch(url, {
      method,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: JSON.stringify(highlightData)
    })
    
    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '保存章节要点配置失败')
    }
    
    const result = await response.json()
    if (result.success) {
      closeModal()
      await loadHighlights()
      
      // 显示成功消息
      alert(isEdit.value ? '更新成功' : '创建成功')
    } else {
      throw new Error(result.message || '保存章节要点配置失败')
    }
  } catch (err) {
    console.error('保存章节要点配置失败:', err)
    error.value = err instanceof Error ? err.message : '保存章节要点配置失败'
  }
}

const toggleStatus = async (highlight: ChapterHighlight) => {
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-highlights/${highlight.id}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${authStore.token}`
      },
      body: JSON.stringify({
        ...highlight,
        isActive: !highlight.isActive
      })
    })
    
    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '更新状态失败')
    }
    
    const result = await response.json()
    if (result.success) {
      await loadHighlights()
    } else {
      throw new Error(result.message || '更新状态失败')
    }
  } catch (err) {
    console.error('切换状态失败:', err)
    error.value = err instanceof Error ? err.message : '更新状态失败'
  }
}

const deleteHighlight = async (highlight: ChapterHighlight) => {
  if (!confirm(`确定要删除章节要点配置"${highlight.title}"吗？此操作不可恢复。`)) {
    return
  }
  
  try {
    const response = await fetch(`${API_BASE_URL}/api/chapter-highlights/${highlight.id}`, {
      method: 'DELETE',
      headers: {
        'Authorization': `Bearer ${authStore.token}`
      }
    })
    
    if (!response.ok) {
      const errorData = await response.json()
      throw new Error(errorData.message || '删除章节要点配置失败')
    }
    
    const result = await response.json()
    if (result.success) {
      await loadHighlights()
      alert('删除成功')
    } else {
      throw new Error(result.message || '删除章节要点配置失败')
    }
  } catch (err) {
    console.error('删除章节要点配置失败:', err)
    error.value = err instanceof Error ? err.message : '删除章节要点配置失败'
  }
}



const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 生命周期
onMounted(() => {
  loadHighlights()
})
</script>

<style scoped>
/* 组件特定样式 */
.truncate {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>